import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as financeApi from '@/api/finance'
import type { FinanceRecord, FinanceListParams, FinanceListResponse } from '@/types'

export const useFinanceStore = defineStore('finance', () => {
  const financeList = ref<FinanceRecord[]>([])
  const loading = ref(false)
  const total = ref(0)

  // 获取财务记录列表
  const fetchFinanceList = async (params: FinanceListParams): Promise<FinanceListResponse> => {
    loading.value = true
    try {
      const response = await financeApi.getFinanceList(params)
      financeList.value = response.list
      total.value = response.total
      return response
    } finally {
      loading.value = false
    }
  }

  // 获取财务记录详情
  const fetchFinanceDetail = async (id: number) => {
    return await financeApi.getFinanceDetail(id)
  }

  // 创建手动记账
  const createManualTransaction = async (data: any) => {
    return await financeApi.createManualTransaction(data)
  }

  // 确认交易
  const confirmTransaction = async (id: number) => {
    return await financeApi.confirmTransaction(id)
  }

  // 取消交易
  const cancelTransaction = async (id: number) => {
    return await financeApi.cancelTransaction(id)
  }

  // 申请退款
  const applyRefund = async (id: number, reason: string) => {
    return await financeApi.applyRefund(id, reason)
  }

  // 批量退款
  const batchRefund = async (ids: number[], reason: string) => {
    return await financeApi.batchRefund(ids, reason)
  }

  // 获取财务统计
  const fetchFinanceStats = async (params?: any) => {
    return await financeApi.getFinanceStats(params)
  }

  // 导出财务数据
  const exportFinanceData = async (params: any) => {
    return await financeApi.exportFinanceData(params)
  }

  return {
    financeList,
    loading,
    total,
    fetchFinanceList,
    fetchFinanceDetail,
    createManualTransaction,
    confirmTransaction,
    cancelTransaction,
    applyRefund,
    batchRefund,
    fetchFinanceStats,
    exportFinanceData
  }
})